# Author: Mike Schladt - 2014
# Malware Intelligence Project 
# FrontEnd - Dashboard View

import os
import sys 
import json 
from django.http import HttpResponse
from django.shortcuts import render

sys.path.append('/home/mike/malware-intelligence-project/frontend/')
import lib.mipsql as mipsql
import lib.allowedtypes as allowedtypes 

def index(request) :
    #grab num analyses, tags and associations to display on homepage
    context = mipsql.get_stats()
    
    #get info for the 10 most recent samples
    most_recent_samples = mipsql.get_most_recent_samples()
    context['most_recent_samples'] = most_recent_samples         
    
    return render(request, 'dashboard/index.html', context)

#function to handle dashboard searching features
#request should include search_text, search_type, and search_table as POST
def search(request):
    #initalize context values
    context = mipsql.get_stats()
    
    #assign local vars to POST parms
    try : 
        search_text = request.POST['search_text'] 
    except : 
        search_text = ""
    try : 
        search_table = request.POST['search_table'] 
    except : 
        search_table = ""
    try : 
        search_type = request.POST['search_type'] 
    except : 
        search_type = ""
        
    search_request = {
        'search_text' : search_text ,
        'search_table' : search_table,
        'search_type' : search_type
    }
    context['search_request'] = search_request
        
    #search the samples table
    if search_table == "sample" and search_text != "" :
        if search_type in allowedtypes.sample_types : # validate form response
            cmd = "SELECT * FROM samples WHERE {0}=%s".format(search_type)
            data = (mipsql.escape_string(search_text)) 
            results = mipsql.execute(cmd, data)
            context['search_results'] = results  
        else :
            context['error'] = "Invalid Input!"
        
        return render(request, 'dashboard/sampleSearch.html', context)    
        
    #search the tags table
    elif search_table == "tag" :
        if search_type in allowedtypes.tag_types : # validate form response
            context['debug'] = search_text
            if search_text != "" : #if search terms are given 
                cmd = "SELECT * FROM tags WHERE type=%s AND MATCH(value) AGAINST(%s) LIMIT 100"
                data = (search_type, mipsql.escape_string(search_text)) 
            else : # without search terms
                cmd = "SELECT * FROM tags WHERE type=%s LIMIT 100"
                data = (search_type) 
                
            results = mipsql.execute(cmd, data)
            context['search_results'] = results  
        else :
            context['error'] = "Invalid Search Type!"
        
        return render(request, 'dashboard/tagSearch.html', context)         

    else : 
        context['error'] = "Invalid Table Type!"
        return render(request, 'dashboard/index.html', context)
